package com.oyjd.business.listview.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.os.AsyncTask;

import com.oyjd.business.listview.util.CountUtil;
import com.oyjd.business.listview.vo.FileVO;
import com.oyjd.framework.Const;
import com.oyjd.framework.log.MyLog;
import com.oyjd.framework.service.CallBack;
import com.oyjd.framework.util.FileOP;
import com.oyjd.framework.util.RandUtil;

/**
 * 读取目录数据列表
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
public class ChengJiService {
	private static final String encoding = "gb2312";
	private static final String TAG = "ChengJiService";

	private int page = 1;
	public int pageSize = 10;

	/**
	 * 首次或刷新获取
	 * 
	 * @param back
	 */
	public void getFirstData(final CallBack back) {
		page = 1;
		new AsyncTask<Integer, Integer, List<FileVO>>() {
			@Override
			protected List<FileVO> doInBackground(Integer... params) {
				int page = params[0];
				int pageSize = params[1];

				int n = page * pageSize;
				return getAllInfo(n - pageSize, n);
			}

			@Override
			protected void onPostExecute(List<FileVO> obj) {
				back.back(obj);
			}
		}.execute(page, pageSize);

	}

	/**
	 * 获取更多
	 * 
	 * @param back
	 */
	public void getMoreData(final CallBack back) {
		page++;
		new AsyncTask<Integer, Integer, List<FileVO>>() {
			@Override
			protected List<FileVO> doInBackground(Integer... params) {
				int page = params[0];
				int pageSize = params[1];

				int n = page * pageSize;
				return getAllInfo(n - pageSize, n);
			}

			@Override
			protected void onPostExecute(List<FileVO> obj) {
				back.back(obj);
			}
		}.execute(page, pageSize);

	}

	/**
	 * 获取文件列表
	 * 
	 * @param start
	 *            开始为位置，包含本身
	 * @param end
	 *            结束位置，不包含本身
	 * @return
	 */
	public static List<FileVO> getAllInfo(int start, int end) {
		List<FileVO> result = new ArrayList<FileVO>();
		List<FileVO> list = new ArrayList<FileVO>();
		File f = new File(Const.APP_DATA_DIR);
		File[] ff = f.listFiles();
		for (File fs : ff) {
			if (fs.isFile() && fs.getName().endsWith("txt")) {
				FileVO vo = new FileVO();
				vo.setFileName(fs.getName());
				vo.setLastTime(fs.lastModified());

				list.add(vo);
			}
		}
		// 按时间排序
		Collections.sort(list, new Comparator<FileVO>() {
			@Override
			public int compare(FileVO o1, FileVO o2) {
				long n1 = o1.getLastTime();
				long n2 = o2.getLastTime();
				if (n1 > n2) {
					return -11;
				} else if (n1 == n2) {
					return 0;
				} else {
					return 1;
				}
			}
		});
		// 抽取集合并读出人数
		if (end > ff.length) {
			end = ff.length;
		}
		for (int i = start; i < end; i++) {
			FileVO vo = list.get(i);
			try {
				String s = FileOP.readFile(Const.APP_DATA_DIR + vo.getFileName(), encoding);
				String[] ss = s.split(CountUtil.split);
				vo.setCount(ss.length);
			} catch (Exception e) {
				MyLog.e(TAG, e.getMessage(), e);
			}
			result.add(list.get(i));
		}
		return result;
	}

	/**
	 * 创建Demo
	 */
	public static void createDemo() {
		File f = new File(Const.APP_DATA_DIR);
		if (f.list().length == 0) {
			int[] n = { 53, 48, 61 };
			for (int j = 0; j < n.length; j++) {
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < n[j]; i++) {
					String s = RandUtil.rand.nextInt(100) + (RandUtil.rand.nextFloat() >= 0.5 ? "" : ".5");
					sb.append(s).append(CountUtil.split);
				}
				try {
					FileOP.writeFile(Const.APP_DATA_DIR + "成绩统计例子" + (j + 1) + ".txt", sb.toString(), encoding);
				} catch (Exception e) {
					MyLog.e(TAG, e.getMessage(), e);
				}
			}
		}
	}

	/**
	 * 保存编辑的文件
	 * 
	 * @param title
	 * @param content
	 * @return
	 */
	public static void saveFile(String title, String c) {
		String fn = Const.APP_DATA_DIR + title + ".txt";
		int pos = 1;
		while (true) {
			if (!new File(fn).exists()) {
				try {
					FileOP.writeFile(fn, c, encoding);
				} catch (Exception e) {
					MyLog.e(TAG, e.getMessage(), e);
				}
				break;
			}
			fn = Const.APP_DATA_DIR + title + "(" + pos + ")" + ".txt";
			pos++;
		}
	}

	/**
	 * 根据文件输出统计HTML
	 * 
	 * @param fileName
	 * @return
	 */
	public String countByFile(String fileName) {
		try {
			String c = FileOP.readFile(Const.APP_DATA_DIR + fileName, encoding);
			String s = CountUtil.count(c);
			return s;
		} catch (Exception e) {
			MyLog.e(TAG, e.getMessage(), e);
		}
		return "读取文件异常：" + fileName;
	}
}
